// 根目录的static下创建js文件夹并创建mixin.js文件
import {
	api
} from "./api.js" //export 导出的api对象文件
export const mixin = {
	data() {
		return {
			api: api, //接口地址
			navbarHeight: Number,
		}
	},
	methods: {
		//封装调用接口的方法,
		post(url, params) {
			let that = this;
			return new Promise((res, rej) => {
				uni.request({
					url: that.$serverUrl + that.api[url], //$serverUrl 在main.js 设置主要的地址
					data: params,
					method: 'POST',
					header: {
						"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
						'Authorization': `Bearer ${window.localStorage.getItem('app_token')}`
					},
					success: (data) => {
						//成功执行res
						res(data)
					},
					fail: (err) => {
						//失败执行rej
						rej(err)
					}
				})
			})
		},
		getNetWorkImg(url) {
			return new Promise((res, rej) => {
				uni.downloadFile({
					url,
					success: (e) => {
						const path = e.tempFilePath;
						if (path.indexOf('json') > -1) {
							rej(path);
							return false;
						}
						res(path)
					},
					fail: (r) => {
						rej(r)
					}
				})
			})
		},
		// 获取图片的主体色值
		async getImgColors(path, canvasId, callback) {
			uni.getImageInfo({
				src: path,
				success: function(img) {
					// 创建一个 Canvas 对象
					const ctx = uni.createCanvasContext(canvasId);
					// 将图片绘制到 Canvas 上
					const imgWidth = 300;
					const imgHeight = 150;
					ctx.drawImage(img.path, 0, 0, imgWidth, imgHeight);
					ctx.save();
					ctx.draw(true, () => {
						uni.canvasGetImageData({
							canvasId: canvasId,
							x: 0,
							y: 0,
							width: imgWidth,
							height: imgHeight,
							success(res) {
								let data = res.data;
								let arr = [];
								let r = 1,
									g = 1,
									b = 1;
								// 取所有像素的平均值
								for (let row = 0; row < imgHeight; row++) {
									for (let col = 0; col < imgWidth; col++) {
										if (row == 0) {
											r += data[imgWidth * row + col];
											g += data[imgWidth * row + col + 1];
											b += data[imgWidth * row + col + 2];
											arr.push([r, g, b]);
										} else {
											r += data[(imgWidth * row + col) * 4];
											g += data[(imgWidth * row + col) * 4 +
												1];
											b += data[(imgWidth * row + col) * 4 +
												2];
											arr.push([r, g, b]);
										}
									}
								}

								// 求取平均值
								r /= imgWidth * imgHeight;
								g /= imgWidth * imgHeight;
								b /= imgWidth * imgHeight;
								// 将最终的值取整
								r = Math.round(r);
								g = Math.round(g);
								b = Math.round(b);

								if (!!callback) {
									// 返回图片主题色的 RGB 颜色值
									callback(`RGB(${r},${g},${b})`);
								}
							},
						});
					});

				},
			});
		},
		// 获取是亮色还是暗色
		hexToRgb(val) {
			if (/^(rgb|RGB)/.test(val)) {
				val = this.convertRgbToHexadecimal(val)
			}
			// 16进制颜色值的正则
			let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
			// 把颜色值变成小写
			let color = val.toLowerCase();
			let result = '';
			if (reg.test(color)) {
				// 如果只有三位的值，需变成六位，如：#fff => #ffffff
				if (color.length === 4) {
					let colorNew = "#";
					for (let i = 1; i < 4; i += 1) {
						colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
					}
					color = colorNew;
				}
				// 处理六位的颜色值，转为RGB
				let colorChange = [];
				for (let i = 1; i < 7; i += 2) {
					colorChange.push(parseInt("0x" + color.slice(i, i + 2)));
				}
				let grayLevel = colorChange[0] * 0.299 + colorChange[1] * 0.587 + colorChange[2] * 0.114;
				if (grayLevel >= 192) { //浅色模式
					return '#000000';
				} else {
					// uniapp页面配置只识别小写
					return '#ffffff';
				}
			} else {
				result = '无效';
				return {
					rgb: result
				};
			}

		},
		// rgb转16进制
		convertRgbToHexadecimal(val) {
			//十六进制颜色值的正则表达式
			let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
			if (/^(rgb|RGB)/.test(val)) {
				let aColor = val.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
				let strHex = "#";
				for (let i = 0; i < aColor.length; i++) {
					let hex = Number(aColor[i]).toString(16);
					if (hex === "0") {
						hex += hex;
					}
					if (hex.length == 1) {
						hex = `0${hex}`
					}
					strHex += hex;
				}
				if (strHex.length !== 7) {
					strHex = val;
				}
				return strHex;
			} else if (reg.test(val)) {
				let aNum = val.replace(/#/, "").split("");
				if (aNum.length === 6) {
					return val;
				} else if (aNum.length === 3) {
					let numHex = "#";
					for (let i = 0; i < aNum.length; i += 1) {
						numHex += (aNum[i] + aNum[i]);
					}
					return numHex;
				}
			} else {
				return val;
			}
		},
		// 16进制转rgb
		convertHexadecimalToRgb(val) {
			//十六进制颜色值的正则表达式
			let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
			let sColor = val.toLowerCase();
			if (sColor && reg.test(sColor)) {
				if (sColor.length === 4) {
					let sColorNew = "#";
					for (let i = 1; i < 4; i += 1) {
						sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
					}
					sColor = sColorNew;
				}
				//处理六位的颜色值
				let sColorChange = [];
				for (let i = 1; i < 7; i += 2) {
					sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
				}
				return "RGB(" + sColorChange.join(",") + ")";
			} else {
				return sColor;
			}
		},
	},
	onReay() {
		let that = this;
		// 获取自定义导航高度 #navbar 自定义导航的高度
		let info = uni.createSelectorQuery().select('#navbar');
		info.boundingClientRect((data) => {
			that.navbarHeight = data.height;
		}).exec();
	}
}